package com.caiyi.financial.nirvana.sms.gateway.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.caiyi.financial.nirvana.sms.entity.SmsReceiveMessage;
import com.caiyi.financial.nirvana.sms.enums.SmsMsgStatusEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.queue.NotifyQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.ReceiveMsgQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ChuanglanGateway extends BaseGateway {

    private static final Logger logger = LoggerFactory.getLogger(ChuanglanGateway.class);

    private static final String SUCCESS = "0";

    @Override
    public void sendMessage(SendQueueEntity entity) {
        int status = SmsMsgStatusEnum.REQUEST_FAIL.index;
        String result = "";
        try {
            String params = buildParams(entity);
            String response = doPost(info.getServerAddr(), params);
            if (response == null) {
                result = "网关请求超时";
                return;
            }
            logger.info("ChuanglanGateway send url : {}, params : {}, result : {}", info.getServerAddr(), params, response);
            Map<String, String> resMap = JSON.parseObject(response, Map.class);
            String code = resMap.get("code");
            if (SUCCESS.equals(code)) {
                status = SmsMsgStatusEnum.REQUEST_SUCCESS.index;
                result = resMap.get("msgId");
            } else {
                result = code + ":" + resMap.get("errorMsg");
            }
        } catch (Exception e) {
            logger.error("ChuanglanGateway sendMessage error ! ", e);
        } finally {
            onSubmitResponse(status, entity.getMessageId(), result);
        }
    }

    private String buildParams(SendQueueEntity entity) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("account", info.getAccount());
        paramsMap.put("password", info.getPassword());
        paramsMap.put("msg", entity.getContent());
        paramsMap.put("phone", entity.getPhone());
        paramsMap.put("report", "true");
        paramsMap.put("extend", entity.getAccessNumber());
        paramsMap.put("uid", entity.getMessageId());
        return JSON.toJSONString(paramsMap);
    }

    @Override
    public boolean notifyStatus(NotifyQueueEntity entity) {
        try {
            String param = entity.getParam();
            logger.info("ChuanglanGateway notifyStatus param : {}", param);
            Map<String, String> paramMap = JSON.parseObject(param, Map.class);
            int status = SmsMsgStatusEnum.SEND_FAIL.index;
            String gatewayStatus = paramMap.get("status");
            if (gatewayStatus.equals("DELIVRD")) {
                status = SmsMsgStatusEnum.SEND_SUCCESS.index;
            }
            String messageId = paramMap.get("uid");
            String result = paramMap.get("statusDesc");
            if (StringUtils.isBlank(messageId)) {
                logger.warn("ChuanglanGateway notifyStatus messageId is null params : {}", param);
            }
            receiveReport(status, messageId, result);
            return true;
        } catch (Exception e) {
            logger.error("ChuanglanGateway notifyStatus error ! ", e);
            return false;
        }
    }

    @Override
    public boolean receiveMsg(ReceiveMsgQueueEntity entity) {
        try {
            String param = entity.getParam();
            logger.info("ChuanglanGateway receiveMsg param : {}", param);
            Map<String, String> paramMap = JSON.parseObject(param, Map.class);
            SmsReceiveMessage smsReceiveMessage = new SmsReceiveMessage();
            String accessNumber = paramMap.get("destcode");
            String extend = accessNumber.substring(accessNumber.length() - 3);
            String account = JedisService.get(String.format(JedisKey.SMS_EXTEND_ACCOUNT, extend));
            String messageId = paramMap.get("spCode");
            String phone = paramMap.get("mobile");
            String content = paramMap.get("msg");
            smsReceiveMessage.setAccount(account);
            smsReceiveMessage.setAccessNumber(accessNumber);
            smsReceiveMessage.setCreateTime(new Date());
            smsReceiveMessage.setPhone(phone);
            smsReceiveMessage.setContent(content);
            smsReceiveMessage.setMessageId(messageId);
            receiveMessage(smsReceiveMessage);
            return true;
        } catch (Exception e) {
            logger.error("ChuanglanGateway receiveMsg error ! ", e);
        }
        return false;
    }

    @Override
    public int queryBalance() {
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("account", info.getAccount());
            paramMap.put("password", info.getPassword());
            String response = HttpClientUtil.doPost(info.getServerAddr().replace("send", "balance"), JSON.toJSONString(paramMap));
            logger.info("{}余额查询结果:{}", info.getName(), response);
            JSONObject res = JSON.parseObject(response);
            if (SUCCESS.equals(res.getString("code"))) {
                return res.getInteger("balance");
            } else {
                logger.error("ChuanglanGateway queryBalance response error : {}{}", res.getString("code"), res.getString("errorMsg"));
            }
        } catch (Exception e) {
            logger.error("ChuanglanGateway queryBalance error ! ", e);
        }
        return 0;
    }
}
